package org.jeecg.modules.monitoring.j_monitoring.service.impl;

import com.alibaba.fastjson.JSON;
import com.sun.org.apache.bcel.internal.generic.I2F;
import com.xkcoding.http.util.StringUtil;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.monitoring.j_monitoring.entity.*;
import org.jeecg.modules.monitoring.j_monitoring.entity.donghuan.AirInfo;
import org.jeecg.modules.monitoring.j_monitoring.entity.donghuan.UpsData;
import org.jeecg.modules.monitoring.j_monitoring.entity.donghuan.realDataRequest;
import org.jeecg.modules.monitoring.j_monitoring.entity.donghuan.realPoints;
import org.jeecg.modules.monitoring.j_monitoring.facilities.FacilitiesToken;
import org.jeecg.modules.monitoring.j_monitoring.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ItScreenService {

    @Resource
    private FacilitiesToken facilitiesToken;
    @Resource
    private RingDevicesMapper devicesMapper;
    @Resource
    private RingMonitorServiceImpl monitorService;
    @Resource
    private RingMonitorMapper monitorMapper;
    @Autowired
    private Environment env;
    @Resource
    private GatewaySystemFdnServiceImpl fdnService;
    @Resource
    private RingWarningMapper ringWarningMapper;
    @Resource
    private NetworkInterfaceLogMapper logMapper;
    @Resource
    private RingSpaceMapper spaceMapper;
    @Resource
    private RingTemLogMapper temLogMapper;



    public List<RingDevices> getUpsIdsList(){
        List<String> nameList = new ArrayList<String>();
        nameList.add("艾默生UPS1");
        nameList.add("艾默生UPS2");
        nameList.add("艾默生UPS3");
        nameList.add("艾默生UPS4");
        List<RingDevices> devicesList = devicesMapper.selectByNameList(nameList);

        return devicesList;
    }
    public List<UpsData> upsRoomInfo(){
        List<UpsData> result = new ArrayList<>();
        //ups列表
        List<RingDevices> devicesList = getUpsIdsList();
        List<String> deviceIdList = devicesList.stream().map(e -> e.getResourceId()).collect(Collectors.toList());

        //ups监控点列表
        List<RingMonitor> monitorList = monitorMapper.selectByParentIds(deviceIdList);


        String json = facilitiesToken.getOnlineData(deviceIdList);

        realDataRequest request = JSON.parseObject(json, realDataRequest.class);
        List<realPoints> pointsList = request.getData().getPoints();
        if (pointsList.size()==0){
            return new ArrayList<>();
        }

        for (RingDevices devices : devicesList){
            UpsData data = new UpsData();
            data.setName(devices.getName());
            for (RingMonitor monitor : monitorList){
                if (!monitor.getParentId().equals(devices.getResourceId())){
                    continue;
                }

                if ("交流输出相电压A".equals(monitor.getName())){
                    String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                    data.setTermVoltageA(value);
                }

                if ("交流输出相电压B".equals(monitor.getName())){
                    String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                    data.setTermVoltageB(value);
                }

                if ("交流输出相电压C".equals(monitor.getName())){
                    String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                    data.setTermVoltageC(value);
                }

                if ("交流输出电流A".equals(monitor.getName())){
                    String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                    data.setOutputCurrentA(value);
                }

                if ("交流输出电流B".equals(monitor.getName())){
                    String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                    data.setOutputCurrentB(value);
                }

                if ("交流输出电流C".equals(monitor.getName())){
                    String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                    data.setOutputCurrentC(value);
                }

                if ("本机A相输出负载百分比".equals(monitor.getName())){
                    String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                    data.setLoadA(value);
                }

                if ("本机B相输出负载百分比".equals(monitor.getName())){
                    String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                    data.setLoadB(value);
                }

                if ("本机C相输出负载百分比".equals(monitor.getName())){
                    String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                    data.setLoadC(value);
                }

                if ("电池后备时间".equals(monitor.getName())){
                    String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                    data.setBatteryTime(value+monitor.getUnit());
                }


            }
            result.add(data);

        }



        return result;
    }


    public Map<String ,Object > itDownInfo(String name){
        Map<String,Object> result = new HashMap<>();
        RingSpace space = spaceMapper.selectByName(name);
        if (space==null){
            return result;
        }

        //告警
        List<RingWarning> warningList = ringWarningMapper.selectByEventSource(name);
        result.put("warningList",warningList);
        result.put("warningCount",warningList.size());
        result.put("haveWarning","无告警");
        for (RingWarning warning : warningList){
            if (warning.getEventSource().contains("空调")){
                result.put("haveWarning","有告警");
            }
        }
        //漏水 和 平均温湿度
        result.put("leakage","无");
        result.put("tem","未检测");
        result.put("hum","未检测");

        List<RingDevices> devicesList = devicesMapper.selectByParentId(space.getResourceId());
        List<String> deviceIdList = devicesList.stream().map(e -> e.getResourceId()).collect(Collectors.toList());

        //监控点列表
        List<RingMonitor> monitorList = monitorMapper.selectByParentIds(deviceIdList);


        String json = facilitiesToken.getOnlineData(deviceIdList);
        if (StringUtil.isEmpty(json)){
            return result;
        }
        realDataRequest request = JSON.parseObject(json, realDataRequest.class);
        if (request==null){
            return result;
        }
        List<realPoints> pointsList = request.getData().getPoints();
        if (pointsList.size()==0){
            return result;
        }

        BigDecimal tem = new BigDecimal(0);//温度
        BigDecimal hum = new BigDecimal(0);//湿度
        int temCount = 0;
        int humCount = 0;

        for (RingMonitor monitor : monitorList){

            if ("温度".equals(monitor.getName())){
                String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);

                if (!StringUtil.isEmpty(value)){
                    tem = tem.add(new BigDecimal(value));
                    temCount++;
                }
            }

            if ("湿度".equals(monitor.getName())){

                String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                if (!StringUtil.isEmpty(value)){
                    humCount++;
                    hum = hum.add(new BigDecimal(value));
                }
            }


            if (monitor.getName().contains("泄露状态")){
                String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                if (value.equals("1")){
                    result.put("leakage","有");
                }
            }

        }
        if(temCount>0){
            BigDecimal temResult = tem.divide(new BigDecimal(temCount),BigDecimal.ROUND_CEILING).setScale(2, RoundingMode.HALF_UP);
            result.put("tem",temResult+"℃");
        }
        if (humCount>0){
            BigDecimal humResult = hum.divide(new BigDecimal(humCount),BigDecimal.ROUND_CEILING).setScale(2, RoundingMode.HALF_UP);
            result.put("hum",humResult+"%");
        }


        return result;
    }

    public Map<String ,Object> getRoomTemHum(String name){
        Map<String,Object> result = new HashMap<>();
        RingSpace space = spaceMapper.selectByName(name);


        //漏水 和 平均温湿度
        result.put("leakage","无");
        result.put("tem",new BigDecimal(0));
        result.put("hum",new BigDecimal(0));

        if (space==null){
            return result;
        }

        List<RingDevices> devicesList = devicesMapper.selectByParentId(space.getResourceId());
        if (devicesList.size() == 0){
            return result;
        }
        List<String> deviceIdList = devicesList.stream().map(e -> e.getResourceId()).collect(Collectors.toList());

        //监控点列表
        List<RingMonitor> monitorList = monitorMapper.selectByParentIds(deviceIdList);
        if (monitorList.size() == 0){
            return result;
        }

        String json = facilitiesToken.getOnlineData(deviceIdList);
        realDataRequest request = JSON.parseObject(json, realDataRequest.class);
        List<realPoints> pointsList = request.getData().getPoints();
        if (pointsList.size()==0){
            return result;
        }

        BigDecimal tem = new BigDecimal(0);//温度
        BigDecimal hum = new BigDecimal(0);//湿度
        int temCount = 0;
        int humCount = 0;

        for (RingMonitor monitor : monitorList){

            if ("温度".equals(monitor.getName())){
                String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);

                if (!StringUtil.isEmpty(value)){
                    tem = tem.add(new BigDecimal(value));
                    temCount++;
                }
            }

            if ("湿度".equals(monitor.getName())){

                String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                if (!StringUtil.isEmpty(value)){
                    humCount++;
                    hum = hum.add(new BigDecimal(value));
                }
            }


            if (monitor.getName().contains("泄露状态")){
                String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                if (value.equals("1")){
                    result.put("leakage","有");
                }
            }

        }
        if(temCount>0){
            BigDecimal temResult = tem.divide(new BigDecimal(temCount),BigDecimal.ROUND_CEILING).setScale(2, RoundingMode.HALF_UP);
            result.put("tem",temResult);
        }
        if (humCount>0){
            BigDecimal humResult = hum.divide(new BigDecimal(humCount),BigDecimal.ROUND_CEILING).setScale(2, RoundingMode.HALF_UP);
            result.put("hum",humResult);
        }


        return result;
    }


    public Map<String,Object> flowList(){
        Map<String,Object> result = new HashMap<>();
        //写死ip设备和端口
        String ip = "10.56.255.254";
        String fdn = fdnService.getFdnByIp(ip,"1");
        if (StringUtil.isEmpty(fdn)){
            return result;
        }
//        List<NetworkInterfaceLog> log100List = logMapper.selectByFdnAndName(fdn,"Eth-Trunk200");

        List<NetworkInterfaceLog> log200List = logMapper.selectByFdnAndName(fdn, "Eth-Trunk100");


        //处理数组数量不一致问题
//        if (log100List.size()>log200List.size() ){
//            for (int i = 0; i < log100List.size()-log200List.size() ; i++) {
//                log100List.remove(i);
//                i--;
//            }
//        }else {
//            for (int i = 0; i < log200List.size()-log100List.size() ; i++) {
//                log200List.remove(i);
//                i--;
//            }
//        }

        result.put("dateList",log200List.stream().map(e -> DateUtils.formatTime(e.getCreateTime())).collect(Collectors.toList()));

        result.put("twoTop",log200List.stream().map(e -> e.getInputRate()).collect(Collectors.toList()));
        result.put("twoDown",log200List.stream().map(e -> e.getOutputRate()).collect(Collectors.toList()));

//        result.put("oneTop",log100List.stream().map(e -> e.getInputRate()).collect(Collectors.toList()));
//        result.put("oneDown",log100List.stream().map(e -> e.getOutputRate()).collect(Collectors.toList()));


        return result;
    }

    public Map<String,Object> airInfo(String name){
        Map<String,Object> result = new HashMap<>();
        List<AirInfo> airInfoList = new ArrayList<>();


        RingSpace space = spaceMapper.selectByName(name);
        if (space==null){
            return result;
        }

        //告警
        List<RingDevices> devicesList = devicesMapper.selectByNameAndParentId("空调","漏水",space.getResourceId());
        List<String> deviceIdList = devicesList.stream().map(e -> e.getResourceId()).collect(Collectors.toList());

        //ups监控点列表
        List<RingMonitor> monitorList = monitorMapper.selectByParentIds(deviceIdList);


        String json = facilitiesToken.getOnlineData(deviceIdList);
        realDataRequest request = JSON.parseObject(json, realDataRequest.class);
        List<realPoints> pointsList = request.getData().getPoints();
        if (pointsList.size()==0){
            return result;
        }

        for (RingDevices devices : devicesList){
            AirInfo data = new AirInfo();
            String[] splitArray = devices.getName().split("#");
            String n = devices.getName().replaceAll(name.toLowerCase(),"").replaceAll(name,"").replaceAll("精密","");
            String[] nArr = n.split("空调");
            data.setName(nArr[0]+splitArray[1] +"#");
            data.setStatus("关闭");
            for (RingMonitor monitor : monitorList){
                if (!monitor.getParentId().equals(devices.getResourceId())){
                    continue;
                }

                if ("机组开关机状态".equals(monitor.getName())){
                    String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                    if ("1".equals(value)){
                        data.setStatus("开启");
                    }else {
                        data.setStatus("关闭");
                    }
                }

                if ("空调开关机状态".equals(monitor.getName())){
                    String value = monitorService.getDataValue(monitor.getResourceId(),pointsList);
                    if ("0".equals(value)){
                        data.setStatus("关闭");
                    }else {
                        data.setStatus("开启");
                    }
                }


            }
            airInfoList.add(data);

        }



        result.put("airInfoList",airInfoList);
        return result;
    }


    public Map<String,Object> temList(String name){

        Map<String,Object> result = new HashMap<>();


        List<RingTemLog> logList =  temLogMapper.selectByName(name);

        result.put("dateList",logList.stream().map(e -> DateUtils.formatTime(e.getCreateTime())).collect(Collectors.toList()));

        result.put("tem",logList.stream().map(e -> e.getTem()).collect(Collectors.toList()));
        result.put("hum",logList.stream().map(e -> e.getHum()).collect(Collectors.toList()));
        return result;
    }
}
